package com.wdcloud.netlibrary.util;

import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.text.TextUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.io.RandomAccessFile;

public class RequestUtil {

    private static final String EXTERNAL_STORAGE_PERMISSION = "android.permission.WRITE_EXTERNAL_STORAGE";
    private static String folderPath = "";
    private static final int MAX_LINES = 200;

    public static void saveRequestToLocalFile(String content) {
        writeFileToSDCard(content, "app_log.txt", true, true);
    }

    public static String getRequestLogFile() {
        folderPath = getRootDirPath()
                + File.separator + "app_log.txt";
        return folderPath;
    }

    /**
     * 此方法为android程序写入sd文件
     *
     * @param content  写入文件的内容
     * @param fileName 文件名称，默认app_log.txt
     * @param append   是否追加写入，true为追加写入，false为重写文件
     * @param autoLine 针对追加模式，true为增加时换行，false为增加时不换行
     */
    public static synchronized void writeFileToSDCard(final String content,
                                                      final String fileName,
                                                      final boolean append, final boolean autoLine) {
        if (TextUtils.isEmpty(content)) {
            return;
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                String folderPath = getRootDirPath();
                File file = null;
                // 判断文件名是否为空
                if (!TextUtils.isEmpty(fileName)) {
                    file = new File(folderPath + File.separator + fileName);
                }

                RandomAccessFile raf = null;
                FileOutputStream out = null;
                try {
                    if (append) {
                        // 如果为追加则在原来的基础上继续写文件
                        raf = new RandomAccessFile(file, "rw");
                        raf.seek(file.length());
                        raf.write(content.getBytes());
                        if (autoLine) {
                            raf.write("\n".getBytes());
                        }
                        // 如果超过100行 重写文件，覆盖掉原来的数据
                        if (getTotalLines(file) > MAX_LINES) {
                            // 重写文件，覆盖掉原来的数据
                            out = new FileOutputStream(file);
                            out.write(content.getBytes());
                            out.flush();
                        }

                    } else {
                        // 重写文件，覆盖掉原来的数据
                        out = new FileOutputStream(file);
                        out.write(content.getBytes());
                        out.flush();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (raf != null) {
                            raf.close();
                        }
                        if (out != null) {
                            out.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    // 文件内容的总行数。
    static int getTotalLines(File file) {
        try {

            FileReader in = new FileReader(file);
            LineNumberReader reader = new LineNumberReader(in);
            String s = reader.readLine();
            int lines = 0;
            while (s != null) {
                lines++;
                s = reader.readLine();
            }
            reader.close();
            in.close();
            return lines;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 获取存储根目录路径
     *
     * @return
     */
    public static String getRootDirPath() {
//        IAppContext appContext = ComponentTransfer.$().getAppContext(COMPONENT_IMPL_APP_CONTEXT);
//        if (appContext == null) {
//            return "";
//        }
//        Context mContext = appContext.AppContext();
//        if (mContext == null) {
//            return "";
//        }
        //TODO 暂时屏蔽
        Context mContext = null;
        if (mContext == null) {
            return "";
        }

        String rootPath = "";
        if (hasExternalStoragePermission(mContext)
                && Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File file = mContext.getExternalFilesDir("");
            if (file != null && file.exists()) {
                rootPath = file.getAbsolutePath();
            } else {
                File dataDir = new File(new File(Environment.getExternalStorageDirectory(), "Android"), "data");
                File filesDir = new File(new File(dataDir, mContext.getPackageName()), "files");
                if (!filesDir.exists()) {
                    if (filesDir.mkdirs()) {
                        rootPath = filesDir.getAbsolutePath();
                    }
                } else {
                    rootPath = filesDir.getAbsolutePath();
                }
            }
        }
        if (TextUtils.isEmpty(rootPath)) {
            rootPath = mContext.getFilesDir().getAbsolutePath();
        }
        return rootPath;
    }


    private static boolean hasExternalStoragePermission(Context context) {
        int perm = context.checkCallingOrSelfPermission(EXTERNAL_STORAGE_PERMISSION);
        return perm == PackageManager.PERMISSION_GRANTED;
    }
}
